﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Customer;
using DataObject.Order;

namespace CMS.Controls.Order
{
    public partial class OrderManager : AuthenticatedControl
    {
        protected int CustomerId;
        protected int PageSize;
        protected int PageIndex;
        protected int OrderComplete;
        protected int OrderTemp;
        protected int OrderDeleted;        

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var ucId = Utils.GetIdFromRequestString(Utils.UserControlId, string.Empty);

            switch (ucId)
            {
                case "od":
                    Control c1 = LoadControl("OrderDetail.ascx");
                    plcControl.Controls.Add(c1);
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CustomerId  = Utils.GetIdFromRequestString(Utils.CustomerId, 0);            
            PageIndex   = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize    = Utils.GetIdFromRequestString(Utils.PageSize, SettingValues.PageSize_40);

            if (!IsPostBack)
            {                
                ListData();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            OrderComplete   = OrderController.Order_GetStatistic((int)OrderStatus.OrderComplete);
            OrderTemp       = OrderController.Order_GetStatistic((int)OrderStatus.OrderTemp);
            OrderDeleted    = OrderController.Order_GetStatistic((int)OrderStatus.OrderDeleted);            
        }

        #endregion

        private void ListData()
        {
            var totalRecords = 0;
            var orders = OrderController.GetListSearch(CustomerId, ConvertUtility.ToInt32(ddlStatus.SelectedValue), PageIndex, PageSize, ref totalRecords);

            lvList.DataSource = orders;
            lvList.DataBind();

            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                                    UrlHelpers.PaginationLinkOrder("{0}", PageSize.ToString()));

            GetStatistics();
        }

        protected static string GetOrderStatus(int status)
        {
            switch (status)
            {
                case (int)OrderStatus.OrderTemp:
                    return "<a title=\"Đặt hàng\" class=\"btn14 topDir\"><img src=\"/images/icons/dark/bag.png\" alt=\"Đặt hàng\"/></a>";
                case (int)OrderStatus.OrderComplete:
                    return "<a title=\"Hoàn thành\" class=\"btn14 topDir\"><img src=\"/images/icons/dark/priceTags.png\" alt=\"Hoàn thành\"/></a>";
                case (int)OrderStatus.OrderDeleted:
                    return "<a title=\"Đã xóa\" class=\"btn14 topDir\"><img src=\"/images/icons/dark/close.png\" alt=\"Đã xóa\"/></a>";
            }
            return string.Empty;
        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var status = ((HiddenField) e.Item.FindControl("hfStatus")).Value;
                var lbRestore = (LinkButton)e.Item.FindControl("lbRestore");
                
                if ((int)OrderStatus.OrderDeleted == ConvertUtility.ToInt32(status))
                    lbRestore.Visible = true;
            }
        }

        protected void lvList_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            var dataItem = (ListViewDataItem)e.Item;
            var id = ConvertUtility.ToInt32(lvList.DataKeys[dataItem.DisplayIndex].Value);

            try
            {
                if (string.Equals(e.CommandName, "DeleteOrder"))
                {
                    if (id > 0)
                    {
                        var o = OrderController.Order_GetById(id);

                        if (o != null)
                        {                            
                            OrderController.Order_Update_Status(id, (int)OrderStatus.OrderDeleted);

                            ltMessage.Text = MessageUtility.ShowMessage(null, "Xóa hóa đơn thành công.", MessageType.Information);

                            ListData();
                        }
                    }
                }
                else if (string.Equals(e.CommandName, "RestoreOrder"))
                {
                    if (id > 0)
                    {
                        var o = OrderController.Order_GetById(id);

                        if (o != null)
                        {
                            OrderController.Order_Update_Status(id, (int)OrderStatus.OrderTemp);

                            ltMessage.Text = MessageUtility.ShowMessage(null, "Khôi phục hóa đơn thành công.", MessageType.Information);

                            ListData();
                        }
                    }
                }
                else if (string.Equals(e.CommandName, "UpdateNote"))
                {
                    if (id > 0)
                    {
                        var note = ((TextBox) e.Item.FindControl("txtNote")).Text;

                        var o = OrderController.Order_GetById(id);

                        if (o != null && !string.IsNullOrEmpty(note))
                        {
                            OrderController.Order_Update_Note(id, note);

                            ltMessage.Text = MessageUtility.ShowMessage(null, "Khôi phục hóa đơn thành công.", MessageType.Information);

                            ListData();
                        }
                        else
                        {
                            ltMessage.Text = MessageUtility.ShowMessage(null, "Nội dung ghi chú không được để trống.", MessageType.Warning);
                            return;
                        }
                    }
                }
            }
            catch
            {
                ltMessage.Text = MessageUtility.ShowMessage(null, "Xóa hóa đơn không thành công.", MessageType.Failure);
            }
        }

        private void UpdateStatus(int targetStatus)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ToInt32(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                {
                    var o = OrderController.Order_GetById(id);
                    if (o != null)
                        OrderController.Order_Update_Status(id, targetStatus);
                }
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn hóa đơn nào.", MessageType.Warning);

            ListData();
            GetStatistics();
        }

        protected void BtnComplete(object sender, EventArgs e)
        {
            UpdateStatus((int) OrderStatus.OrderComplete);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            UpdateStatus((int)OrderStatus.OrderDeleted);
        }

        protected void BtnSearch(object sender, EventArgs e)
        {
            ddlCustomer.Items.Clear();

            var typeId = ConvertUtility.ToInt32(ddlType.SelectedValue);
            var keyword = txtSearch.Text;

            var lstCustomer = CustomerController.GetListSearch(typeId, keyword);
            if (lstCustomer != null && lstCustomer.Rows.Count > 0)
            {
                for (int i = 0; i < lstCustomer.Rows.Count; i++)
                {
                    ddlCustomer.Items.Add(new ListItem(string.Format("{0} - {1}",
                                                lstCustomer.Rows[i]["ContactName"], lstCustomer.Rows[i]["Mobile"]),
                                                lstCustomer.Rows[i]["CustomerId"].ToString()));
                }
                ddlCustomer.Visible = true;                     
            }
            else
            {
                ltLabel.Text = "Không có khách hàng nào!";
                ddlCustomer.Visible = false;
            }
            ddlCustomer.Items.Insert(0, "-- Khách hàng --");
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListData();
        }

        protected void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            var status      = ConvertUtility.ToInt32(ddlStatus.SelectedValue);
            var customerId  = ConvertUtility.ToInt32(ddlCustomer.SelectedValue);
            if (customerId > 0)
                Response.Redirect(string.Format("Default.aspx?cId={0}&cusId={1}&status={2}", cControl.AdminMenuId, customerId, status));                
        }        
    }
}